package com.cskaoyan.service.impl;

import com.cskaoyan.bean.BrandListParameter;
import com.cskaoyan.mapper.MarketBrandMapper;
import com.cskaoyan.model.MarketBrand;
import com.cskaoyan.model.MarketBrandExample;
import com.cskaoyan.service.BrandService;
import com.cskaoyan.utils.MyBatisUtil;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.session.SqlSession;

import java.util.Date;
import java.util.List;

public class BrandServiceImpl implements BrandService {
    @Override
    public List<MarketBrand> list(BrandListParameter parameter) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        MarketBrandMapper brandMapper = sqlSession.getMapper(MarketBrandMapper.class);
        PageHelper.startPage(parameter.getPage(), parameter.getLimit());
        MarketBrandExample example = new MarketBrandExample();
        example.setOrderByClause(parameter.getSort()+" "+parameter.getOrder());
        MarketBrandExample.Criteria criteria = example.createCriteria();
        if (parameter.getId() != null && parameter.getId()!=0) {
            criteria.andIdEqualTo(parameter.getId());
        }
        String name = parameter.getName();
        if (name != null && !name.isEmpty()) {
            criteria.andNameLike("%"+name+"%");
        }
        criteria.andDeletedEqualTo(false);
        List<MarketBrand> marketBrands = brandMapper.selectByExample(example);
        sqlSession.commit();
        sqlSession.close();
        return marketBrands;
    }

    @Override
    public MarketBrand create(MarketBrand marketBrand) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        MarketBrandMapper brandMapper = sqlSession.getMapper(MarketBrandMapper.class);
        Date date = new Date();
        marketBrand.setAddTime(date);
        marketBrand.setUpdateTime(date);
//        marketBrand.setDeleted(false);
        brandMapper.insertSelective(marketBrand);
        sqlSession.commit();
        sqlSession.close();
        return marketBrand;
    }

    @Override
    public MarketBrand update(MarketBrand marketBrand) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        MarketBrandMapper brandMapper = sqlSession.getMapper(MarketBrandMapper.class);
        marketBrand.setUpdateTime(new Date());
        brandMapper.updateByPrimaryKeySelective(marketBrand);
        sqlSession.commit();
        sqlSession.close();
        return marketBrand;
    }

    @Override
    public void delete(MarketBrand marketBrand) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        MarketBrandMapper brandMapper = sqlSession.getMapper(MarketBrandMapper.class);
        marketBrand.setDeleted(true);// 逻辑删除
        brandMapper.updateByPrimaryKeySelective(marketBrand);
//        brandMapper.deleteByPrimaryKey(marketBrand.getId());// 物理删除
        sqlSession.commit();
        sqlSession.close();
    }
}
